package com.tjetc.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tjetc.common.Result;
import com.tjetc.config.AlipayConfig;
import com.tjetc.dao.UserDao;
import com.tjetc.dao.impl.UserDaoImpl;
import com.tjetc.domain.Profit;
import com.tjetc.domain.User;
import com.tjetc.service.FeeService;
import com.tjetc.service.ProfitService;
import com.tjetc.service.UserService;
import com.tjetc.service.impl.FeeServiceImpl;
import com.tjetc.service.impl.ProfitServiceImpl;
import com.tjetc.service.impl.UserServiceImpl;
import com.tjetc.utils.TimeUtil;
import com.tjetc.utils.ValidateCodeUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.*;

@WebServlet("/front/*")
@MultipartConfig
public class FrontServlet extends HttpServlet {
    private final static String SignName = "杜鑫磊的系统";
    private final static String TemplateCode = "SMS_463155405";
    private FeeService feeService = new FeeServiceImpl();
    private UserService userService = new UserServiceImpl();
    private UserDao userDao = new UserDaoImpl();
    private ProfitService profitService = new ProfitServiceImpl();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uri = request.getRequestURI();
        String methodName = uri.substring(uri.lastIndexOf("/") + 1);
        try {
            Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this, request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void sendMsg(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String phone = request.getParameter("phone");
        if (phone != "" && phone != null) {
            //生成随机4或者6位验证码
            String code = ValidateCodeUtils.generateValidateCode(6).toString();
            System.out.println("code = " + code);
            //调用阿里云api
            //SMSUtils.sendMessage(SignName,TemplateCode,phone,code);
            //需要将生成的验证码保存到redis
            /*Jedis jedis = JedisDb.jedis();
            jedis.set(phone, code);
            jedis.expire(phone, 5 * 60L);*/
            //将生成的验证码存储到session中
            // 获取会话对象
            /*HttpSession session = request.getSession();

            // 在会话中存储字段
            session.setAttribute("code", code);
            System.out.println(session.getAttribute("code"));*/

            new ObjectMapper().writeValue(response.getOutputStream(),code);
        }
    }

    protected void checkMsg(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String phone = request.getParameter("phone");
        //String code = request.getParameter("code");
        User user = userService.getByPhone(phone);
        if (user == null) {
            int min = 1000000;
            int max = 9999999;
            User newUser = new User();
            //随机生成昵称
            newUser.setName("kailaimei"+new Random().nextInt(max - min + 1));
            newUser.setPhone(phone);
            userService.add(newUser);
            Integer newUserId = userService.getMaxId();
            User maxUser = userService.getById(newUserId);
            new ObjectMapper().writeValue(response.getOutputStream(), Result.success(maxUser,"NewUser"));
        }else{
            new ObjectMapper().writeValue(response.getOutputStream(), Result.success(user,"BingGo"));
        }
//        Jedis jedis = JedisDb.jedis();
//        String codeInRedis = jedis.get(phone);
//
//        if (code != "" && code.equals(codeInRedis)) {
//            new ObjectMapper().writeValue(response.getOutputStream(), Result.success(user,"BingGo"));
//        } else {
//            new ObjectMapper().writeValue(response.getOutputStream(), Result.fail("Fail"));
//        }
    }

    protected void refund(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl,
                AlipayConfig.app_id, AlipayConfig.merchant_private_key,
                "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();

        //接受用户id，
        String id = new String(request.getParameter("id").getBytes("ISO-8859-1"),"UTF-8");
        //商户订单号，商户网站订单系统中唯一订单号
        String out_trade_no = new String(request.getParameter("WIDTRout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //支付宝交易号
        String trade_no = new String(request.getParameter("WIDTRtrade_no").getBytes("ISO-8859-1"),"UTF-8");
        //请二选一设置
        //需要退款的金额，该金额不能大于订单金额，必填
        String refund_amount = new String(request.getParameter("WIDTRrefund_amount").getBytes("ISO-8859-1"),"UTF-8");
        System.out.println("refund_amount = " + refund_amount);
        //退款的原因说明
        String refund_reason = new String(request.getParameter("WIDTRrefund_reason").getBytes("ISO-8859-1"),"UTF-8");
        //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
        String out_request_no = new String(request.getParameter("WIDTRout_request_no").getBytes("ISO-8859-1"),"UTF-8");

        //执行清空user表的account
        userService.clearAccount(Integer.valueOf(id));

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"trade_no\":\""+ trade_no +"\","
                + "\"refund_amount\":\""+ refund_amount +"\","
                + "\"refund_reason\":\""+ refund_reason +"\","
                + "\"out_request_no\":\""+ out_request_no +"\"}");

        //请求
        String result = null;
        try {
            result = alipayClient.execute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        System.out.println("result = " + result);
        //输出
        response.getWriter().write(result);
    }

    //充值
    protected void reCharge(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
                AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key,
                AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //付款金额，必填
        String total_amount = new String(request.getParameter("WIDtotal_amount").getBytes("ISO-8859-1"),"UTF-8");
        //订单名称，必填
        String subject = new String(request.getParameter("WIDsubject").getBytes("ISO-8859-1"),"UTF-8");
        //商品描述，可空
        String body = new String(request.getParameter("WIDbody").getBytes("ISO-8859-1"),"UTF-8");
        //用户序号
        String id = new String(request.getParameter("id").getBytes("ISO-8859-1"),"UTF-8");
        User user = userService.getById(Integer.valueOf(id));
        try {//修改账户金额
            user.setId(Integer.valueOf(id));
            user.setAccount(user.getAccount()+Double.valueOf(total_amount));
            userDao.update(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //存入当日营收额中
        Date date = new Date();
        String nowDate = TimeUtil.timeYmd(date);
        Profit profit = profitService.findByDate(nowDate);
        if (profit != null){//累加金额
            profit.setTotal(profit.getTotal()+Double.valueOf(total_amount));
            profitService.updateProfit(profit);
        }else{//今日第一笔钱
            Profit newPro = new Profit();
            newPro.setTotal(Double.valueOf(total_amount));
            newPro.setDate(nowDate);
            profitService.addProfit(newPro);
        }
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = null;
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        //输出
        response.getWriter().write(result);
    }

    //单独付钱
    protected void JumpTo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
                AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key,
                AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //缴费序号
        String id = new String(request.getParameter("id").getBytes("ISO-8859-1"),"UTF-8");
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //付款金额，必填
        String total_amount = new String(request.getParameter("WIDtotal_amount").getBytes("ISO-8859-1"),"UTF-8");
        //订单名称，必填
        String subject = new String(request.getParameter("WIDsubject").getBytes("ISO-8859-1"),"UTF-8");
        //商品描述，可空
        String body = new String(request.getParameter("WIDbody").getBytes("ISO-8859-1"),"UTF-8");

        //修改缴费状态
        feeService.updateStatus(Integer.parseInt(id));

        //存入当日营收额中
        Date date = new Date();
        String nowDate = TimeUtil.timeYmd(date);
        Profit profit = profitService.findByDate(nowDate);
        if (profit != null){//累加金额
            profit.setTotal(profit.getTotal()+Double.valueOf(total_amount));
            profitService.updateProfit(profit);
        }else{//今日第一笔钱
            Profit newPro = new Profit();
            newPro.setTotal(Double.valueOf(total_amount));
            newPro.setDate(nowDate);
            profitService.addProfit(newPro);
        }
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        //请求
        String result = null;
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        //输出
        response.getWriter().write(result);
    }

    //回调页面
    protected void check(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = false; //调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key,
                    AlipayConfig.charset, AlipayConfig.sign_type);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            if (out_trade_no == "" && out_trade_no.length() == 0){//如果这数据为空，代表交易未完成，所以该缴费状态为0
                feeService.rollBackStatus();
            }
            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
            System.out.println("trade_no = " + trade_no);
            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
            response.sendRedirect("http://localhost:9528/#/front/fee");
        }else {
            response.getWriter().write("验签失败");
        }
    }
}
